﻿using System;
using System.Web.UI.WebControls;
using System.Data;
using SQLHelper;

public partial class admin_Column_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int index = Convert.ToInt32(Request["edit"]);

        if (Request["edit"] != null)
        {
            GridView1.EditIndex = index;
        }

        if (Request["del_id"] != null)
        {
            Delete();
        }

        if (!this.IsPostBack)
        {
            bind();
        }

        if(this.IsPostBack)
        {
            if(Request["edit"] != null)
            {
                ViewState["column_name"] = ((TextBox)GridView1.Rows[index].Cells[1].Controls[0]).Text.ToString();
                ViewState["description"] = ((TextBox)GridView1.Rows[index].Cells[2].Controls[0]).Text.ToString();
                update();
            }
        }
    }

    // 新增数据
    protected void Create(object sender, EventArgs e)
    {
        string newColumn = TextBox1.Text.ToString().Trim();
        string newDescription = TextBox1.Text.ToString().Trim();
        string sql = "insert into columns (column_name, description) values('" + newColumn + "', '" + newDescription + "')";
        DB.GetDataNoQuery(sql);
        DB.ColseSqlCon();
        Response.Redirect("Default.aspx");
    }

    // 删除数据
    void Delete()
    {
        int id = Convert.ToInt32(Request["del_id"]);
        string sqlstr = "delete from columns where id='" + id + "'";
        DB.GetDataNoQuery(sqlstr);
        DB.ColseSqlCon();
        Response.Redirect("Default.aspx");
    }

    // 编辑数据
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bind();
    }

    // 更新数据的具体方法
    void update()
    {
        int id = Convert.ToInt32(Request["id"]);
        int index = Convert.ToInt32(Request["edit"]);
        string newColumn = Convert.ToString(ViewState["column_name"]);
        string newDescription = Convert.ToString(ViewState["description"]);
        string sqlstr = "update columns set column_name='"
            + newColumn.Trim() + "',description='"
            + newDescription.Trim() + "' where id='"
            + id + "'";
        DB.GetDataNoQuery(sqlstr);
        DB.ColseSqlCon();
        Response.Redirect("Default.aspx");
    }

    // 更新数据的动作
    protected void GridView1_RowUpdating(object sender, EventArgs e)
    {
        GridView1.EditIndex = -1;
        bind();
    }

    // 取消编辑
    protected void GridView1_RowCancelingEdit(object sender, EventArgs e)
    {
        GridView1.EditIndex = -1;
        bind();
    }

    // 绑定数据
    public void bind()
    {
        string sqlStr = "select * from columns";
        DataSet res = DB.GetDataWithQuerySecond(sqlStr, "columns");
        GridView1.DataSource = res;
        GridView1.DataKeyNames = new string[] { "id" };//主键
        GridView1.DataBind();
        DB.ColseSqlCon();
    }
}